package org.shop.weixin.servlet;

import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.shop.weixin.pojo.SNSUserInfo;
import org.shop.weixin.util.AdvancedUtil;
import org.shop.weixin.util.WeixinOauth2Token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 授权后的回调请求处理
 *
 * @author
 * @date 2013-11-12
 */
@Controller("workerOAuthController")
@RequestMapping("/admin/workerOAuth")
public class WorkerOAuthServlet {

    private static Logger log = LoggerFactory.getLogger(WorkerOAuthServlet.class);
    @Value("${workerappid}")
    private String workerappid;
    @Value("${workerappsecret}")
    private String workerappsecret;


    @RequestMapping(method = RequestMethod.GET)
    public String doGet(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                        HttpSession session) throws ServletException, IOException {
  
        /**
         * 根据进入方式不同，进入到不同的页面。
         * 进入方式分送水工从微信端进入和从电脑端登录
         */
        log.info("进入页面--------根据进入方式不同，进入到不同的页面--");
     
            String code = request.getParameter("code");

            log.info("进入页面--------根据从微信端发起的http请求，接收到微信发送来的code--" + code);

            log.info("进入页面--------根据从微信端发起的http请求，检查用户是否授权：--" + (!"authdeny".equals(code)));
            //
            // 用户同意授权
            if (!"authdeny".equals(code)) {
                log.info("进入页面--------根据从微信端发起的http请求，用户已经授权：--");
                // 获取网页授权access_token

                WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken(
                		workerappid, workerappsecret, code);
                // 网页授权接口访问凭证
                String accessToken = weixinOauth2Token.getAccessToken();
                log.info("进入送水工授权页面--------用户同意授权的code数据获取网页授权接口访问凭证--" + accessToken);

                // 用户标识
                String openId = weixinOauth2Token.getOpenId();
                log.info("进入送水工授权页面--------用户openID--" + openId);

                // 获取用户信息
                SNSUserInfo snsUserInfo = AdvancedUtil.getSNSUserInfo(accessToken, openId);

                /*根据配送人员信息，配送人员微信从snsUserInfo读取*/
               
                String toUri = request.getParameter("to");
                //跳转商城主页
                return "redirect:/" + toUri;
            
        }
        return null;
    }
}
